package com.maple.phoneward.custom.lockpattern;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;

import com.maple.phoneward.activity.MainActivity;
import com.maple.phoneward.activity.R;
import com.maple.phoneward.custom.DialogBuilder;
import com.maple.phoneward.utils.AppUtil;
import com.maple.phoneward.utils.StringUtil;

public class LockLayer {
	private Activity mActivty;
	private WindowManager mWindowManager;
	private View mLockView;
	private LayoutParams mLockViewLayoutParams;
	private static LockLayer mLockLayer;
	private boolean isLocked;
	// apktool value，这个值具体是哪个变量还请网友帮忙。用于实现全屏
	private final static int FLAG_APKTOOL_VALUE = 1280;

	public static synchronized LockLayer getInstance(Activity act) {
		if (mLockLayer == null) {
			mLockLayer = new LockLayer(act);
		}
		return mLockLayer;
	}

	private LockLayer(Activity act) {
		mActivty = act;
		init();
	}

	private void init() {
		isLocked = false;
		mWindowManager = mActivty.getWindowManager();
		mLockViewLayoutParams = new LayoutParams();
		mLockViewLayoutParams.width = LayoutParams.MATCH_PARENT;
		mLockViewLayoutParams.height = LayoutParams.MATCH_PARENT;
		// 这一行实现屏蔽Home
		mLockViewLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;
		mLockViewLayoutParams.flags = FLAG_APKTOOL_VALUE;
	}

	public synchronized void lock() {
		if (mLockView != null && !isLocked) {
			mWindowManager.addView(mLockView, mLockViewLayoutParams);
		}
		isLocked = true;
	}

	public synchronized void unlock() {
		if (mWindowManager != null && isLocked) {
			mWindowManager.removeView(mLockView);
		}
		isLocked = false;
	}

	public synchronized void setLockView(View v) {
		mLockView = v;
	}

	// =============
	public synchronized void showDialog(final Context context, final String pwd, boolean flag) {
		unlock();
		final EditText editText = new EditText(context);
		editText.setHint(R.string.step_1_not_null);
		Dialog dialog = new DialogBuilder(context)//
				.setTitle(R.string.step_1_not_null)//
				.setView(editText)//
				.setOnClickListener(null)//
				.create();
		dialog.show();
		dialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				String input = editText.getText().toString();
				if (StringUtil.isNotEmpty(input) && StringUtil.equals(input, pwd)) {
					Intent intent = new Intent(context, MainActivity.class);
					context.startActivity(intent);
				} else {
					lock();
					AppUtil.showShortMessage(context, R.string.phoneward_pwd_wrong);
				}
			}
		});
	}
}
